package org.supda.system.task;

import java.util.Collection;
import java.util.List;

import javax.inject.Inject;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.supda.system.entity.TMessageSend;
import org.supda.system.entity.TUser;
import org.supda.system.service.TMessageSendService;

/**
 * 
 * @author supda
 * @date 2017-3-11
 * 消息推送
 */
@Service
@Lazy(false) 
public class MessageCountScheduledTask {
	
	@Autowired private TMessageSendService messageSendService;
	
	//此处无法使用注解,BUG？
	public  static SimpMessageSendingOperations simpMessageSendingOperations;
	
	@Autowired private SessionDAO sessionDAO;
	
    @Scheduled(cron="0/10 * *  * * ? ")   //每10秒执行一次   
    public void trigger() {
    	
    	messageScheduledTask();
    }
    
    //消息缓冲区刷新
    private void messageScheduledTask(){
    	
		Collection<Session> sessions =sessionDAO.getActiveSessions();
		
		//给所有在线的用户推送消息提醒，每1s检查一次是否有消息需要推送
		for(Session session:sessions){

			TUser user = (TUser) session.getAttribute("userSession");
			
			if(user!=null && user.getId()!=null && user.getId() >0L ){
				List<TMessageSend> lists = messageSendService.selectUnSendMessages(user.getId());
				
				MessageMapSingleton.getInstance().setAttribute(user.getId(), lists);
				
				//给所有在线的用户推送消息提醒，每1s检查一次是否有消息需要推送
				if(simpMessageSendingOperations != null && lists!=null && lists.size()!=0)
					simpMessageSendingOperations.convertAndSendToUser(user.getAccountName(), "/queue/message", 
							lists.size());
			}
		}
    }
}
